<template>
  <div class="open-layout">
    <div class="header">
      <div class="header_span">
        <cell-header title="智能拓词" :type="1"></cell-header>
      </div>
    </div>
    <el-card shadow="never" style="position: relative;top: 40px;overflow:hidden;">
      <div class="detail-main">
        <div class="search-box flex">
          <div class="lt-box flex">
            <span class="title">拓词分区</span>
            <el-select v-model="queryData.country" placeholder="请选择" size="small" style="max-width: 120px;" @change="handleChangeCountry">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <powerSearch class="btn" :query-data="{...queryData.openUpWordCondition}" @click.native="highSearchShow=true"></powerSearch>
          </div>

          <div class="rt flex">

            <el-input v-model.trim="searchStr" placeholder="输入关键词" size="small" class="input-box" @keyup.enter.native="handleSearch">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="handleSearch"></i>
            </el-input>

            <el-button type="success" @click="handleSearch">
              <span style="font-size: 14px;line-height: 14px;">拓词</span>
            </el-button>
          </div>

        </div>

        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          @selection-change="handleSelecChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" fixed="left">
          </el-table-column>
          <el-table-column label="关键词" show-overflow-tooltip width="230" fixed="left">
            <template slot-scope="scope">
              <span v-html="scope.row.copyKeyword "></span>
            </template>
          </el-table-column>

          <el-table-column prop="asaPopular" label="ASA流行度" width="130" align="left" sortable sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.asaPopular*1?scope.row.asaPopular:'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="asoSearch" label="AppStore搜索指数" width="180" align="left" sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.asoSearch*1?scope.row.asoSearch:'-' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="searchCount" label="AppStore搜索结果数" width="200" align="left" sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.searchCount*1?scope.row.searchCount:'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="googleSearch" label="谷歌搜索指数" width="150" align="left" sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.googleSearch*1?scope.row.googleSearch:'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="youtubeSearch" label="YouTube搜索指数" width="180" align="left" sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.youtubeSearch*1?scope.row.youtubeSearch:'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="baiduPc" label="百度PC搜索指数" width="180" align="left" sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.baiduPc*1?scope.row.baiduPc:'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="baiduMb" label="百度移动搜索指数" width="180" align="left" sortable="custom">
            <template slot-scope="scope">
              <span> {{ scope.row.baiduMb*1?scope.row.baiduMb:'-' }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column prop="dySearch" label="抖音搜索指数" width="150" align="center" sortable>
          </el-table-column> -->
          <!-- <el-table-column prop="ttSearch" label="头条搜索指数" width="150" align="center" sortable>
          </el-table-column> -->

          <el-table-column prop="popu" label="操作" width="130" align="center" fixed="right">
            <template slot-scope="scope">
              <p class="flex">
                <em class="pointer" @click="handleAddTo([scope.row])">添加至</em>
                <em class="pointer" @click="handleToSearch( scope.row)">拓词</em>
              </p>
            </template>
          </el-table-column>
          <el-table-column>
          </el-table-column>

        </el-table>
        <div class="block" style="padding-top: 24px;display: flex;justify-content: flex-end;margin-bottom: 50px;">
          <el-pagination
            :current-page="queryData.pageNum"
            :page-sizes="[30,50,100,150,200]"
            :page-size="30"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </div>

    </el-card>
    <hint-box v-if="selectList.length" :num="selectList.length">
      <div class="flex hint-rt ">
        <span class="pointer" @click="handleAddTo(selectList)">批量添加至</span>
      </div>
    </hint-box>

    <el-dialog title="添加至" :visible.sync="dialogFormVisible" class="dia" width="600px">
      <el-form ref="addForm" :model="form" label-position="top">
        <el-form-item label="添加至">
          <el-radio-group v-model="form.type">
            <el-radio label="adgroup">
              <p class="webfont-Regular" style="display: inline-block;">广告组</p>
            </el-radio>
            <el-radio label="wordStore">

              <p class="webfont-Regular" style="display: inline-block;">词库</p>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.type==='adgroup'"
          label="添加至"
          prop="adList"
          :rules="[
            { required: true, message: '请选择广告组', trigger: 'blur' }]"
        >
          <chooseAdgroup v-model="form.adList"></chooseAdgroup>
        </el-form-item>
        <el-form-item
          v-else
          label="添加至"
          :rules="[
            { required: true, message: '请选择词库', trigger: 'blur' }]"
          prop="storeList"
        >
          <chooseWordStore v-model="form.storeList"></chooseWordStore>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancel-btn defult" @click="handleCloseSub">取 消</el-button>
        <el-button type="success" class="defult" @click="handleSubAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 高级筛选  拓词 -->
    <el-dialog title="高级筛选" :visible.sync="highSearchShow" width="600px" class="bottom-dia" @open="handlerOpenHighSearch">
      <el-form :model="searchForm" :label-position="'top'" size="small">
        <el-row :gutter="80">
          <el-col :span="12">
            <el-form-item label="包含">
              <el-input v-model="searchForm.include" autocomplete="off" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不包含">
              <el-input v-model="searchForm.denyWorder" autocomplete="off" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ASA流行度">
              <intervalInput v-model="searchForm.asaPopular" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="App Store搜索指数">
              <intervalInput v-model="searchForm.asoSearch" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="App Store搜索结果数">
              <intervalInput v-model="searchForm.searchCount" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="谷歌搜索指数">
              <intervalInput v-model="searchForm.googleSearch" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="YouTube搜索指数">
              <intervalInput v-model="searchForm.youtubeSearch" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="百度PC搜索指数">
              <intervalInput v-model="searchForm.baiduPc" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="百度移动搜索指数">
              <intervalInput v-model="searchForm.baiduMb" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer flex">

        <em style="font-size: 14px;" @click="resetSearForm">重置</em>
        <div>
          <el-button class="cancel-btn defult" @click="highSearchShow=false">取消</el-button>
          <el-button type="success" class="defult" @click="handlerHighSearch">应用</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import cellHeader from '@/components/cell-header.vue'
import hintBox from '@/components/hintBox/index.vue'
import chooseAdgroup from '../components/chooseAdgroup.vue'
import chooseWordStore from '../components/chooseWordStore.vue'
import {
  addWordsToStore, // 添加关键词到词库
  recommendWordShiftAdvGroup, // 添加词到广告组
  findOpenUpWords // 拓词接口

} from '@/api/tool.js'

export default {
  name: '', // ·������
  components: {
    cellHeader,
    hintBox,
    chooseAdgroup,
    chooseWordStore

  },
  data() {
    return {
      timer: undefined,
      loading: false,
      options: [{
        value: 'US',
        label: '海外市场'
      },
      {
        value: 'CN',
        label: '中国市场'
      }
      ],
      searchStr: '',
      total: 0,
      queryData: {
        country: 'US', // 国家
        order: 'descending', // 正序或者倒叙：descending、ascending
        prop: 'asaPopular', // 排序字段：asaPopular、asoSearch、searchCount、baiduPc、baiduMb、dySearch、ttSearch、googleSearch、youtubeSearch
        pageNum: 1,
        pageSize: 30,
        teamId: '',
        text: '', // 搜索词
        openUpWordCondition: {
          include: '', // 包含关键词
          denyWorder: '', // 不包含关键词
          asaPopularMin: '', // 最小ASA 流行度
          asaPopularMax: '', // 最大ASA 流行度
          asoSearchMin: '', // 最小App Store 搜索指数
          asoSearchMax: '', // 最大App Store 搜索指数
          searchCountMin: '', // 最小App Store 搜索结果数
          searchCountMax: '', // 最大App Store 搜索结果数
          baiduMbMin: '', // 最小百度移动搜索指数
          baiduMbMax: '', // 最大百度移动搜索指数
          baiduPcMin: '', // 最小百度pc搜索指数
          baiduPcMax: '', // 最大百度pc搜索指数
          youtubeSearchMin: '', // 最小youtube 搜索指数
          youtubeSearchMax: '' // 最大youtube 搜索指数
        }
      },
      selectList: [], // 多选的表格数据
      tableData: [],
      dialogFormVisible: false,
      addList: [], // 要添加的词
      form: {
        type: 'adgroup',
        adList: [],
        storeList: []
      },
      highSearchShow: false,
      searchForm: {
        include: '', // 包含
        denyWorder: '', // 不包含
        asaPopular: {
          min: undefined,
          max: undefined
        }, // ASA流行度
        asoSearch: {
          min: undefined,
          max: undefined
        }, // App Store搜索指数
        searchCount: {
          min: undefined,
          max: undefined
        }, // App Store搜索结果数
        googleSearch: {
          min: undefined,
          max: undefined
        }, // 谷歌搜索指数
        youtubeSearch: {
          min: undefined,
          max: undefined
        }, // YouTube搜索指数
        baiduPc: {
          min: undefined,
          max: undefined
        }, // 百度Pc搜索指数
        baiduMb: {
          min: undefined,
          max: undefined
        } // 百度移动搜索指数

      }
    }
  },
  computed: {
    teamId() {
      this.queryData.teamId = this.$store.state.team.teamId
      return this.$store.state.team.teamId
    }
  },
  watch: {
    // obj: { //�����Ķ���
    //   deep: true, //���ȼ�������Ϊ true
    //   // ������wacth��������firstName��������֮��������ȥִ��handler����
    //       immediate: true
    //   handler: function(newV, oldV) {
    //     console.log('watch�У�', newV)
    //   }
    // }
    // 鸡36 猪41 鼠51
  },
  // ������
  created() {},
  // ���غ�
  mounted() {
    // console.log(this.queryData)
  },
  // ���ٺ�
  destroyed() {

  },

  // ����
  methods: {
    handleChangeCountry() {
      if (!this.queryData.text) return false
      this.queryData.pageNum = 1
      this.getOpenWords()
    },

    async getOpenWords() {
      try {
        this.loading = true
        const res = await findOpenUpWords(this.queryData)
        this.loading = false
        /* console.log(res, '拓词的结果') */
        if (res.data.code * 1 === 20000 && res.data.data.list && res.data.data.list[0] !== null) {
          this.total = res.data.data.count
          this.tableData = res.data.data.list.map(item => {
            return {
              ...item,
              copyKeyword: item.keyword.replace(/\ /g, '&nbsp;')
            }
          })
        } else {
          this.total = 0
          this.tableData = []
          this.$message.closeAll()
          // console.log(res)
          this.$message.error(res.data.message || '数据获取失败,请稍候刷新重试')
        }
      } catch (err) {
        // console.log(err,'你好错误')
        this.total = 0
        this.tableData = []
        // this.$message.closeAll()
        // this.$message.error(err.data.message || '数据获取失败,请稍候刷新重试')
      }
    },
    handleSortChange(data) {
      // console.log(data)
      if (data.order) {
        this.queryData.order = data.order
        this.queryData.prop = data.prop
      } else {
        this.queryData.order = 'descending'
        this.queryData.prop = 'asaPopular'
      }
      this.queryData.pageNum = 1
      if (!this.queryData.text) return false
      this.getOpenWords()
    },

    handleSizeChange(size) {
      this.queryData.pageSize = size
      this.queryData.pageNum = 1
      if (!this.queryData.text) return false
      this.getOpenWords()
    },
    handleCurrentChange(index) {
      this.queryData.pageNum = index
      /* if (!this.searchStr) return false */
      this.getOpenWords()
    },
    handleSelecChange(data) {
      this.selectList = JSON.parse(JSON.stringify(data))
    },
    handleSearch() {
      // console.log(this.timer, '你好电石气')
      if (this.timer) {
        return false
      }

      this.queryData.text = this.searchStr
      this.queryData.pageNum = 1
      if (!this.searchStr) {
        this.total = 0
        this.tableData = []

        return false
      }
      this.getOpenWords()
      this.timer = setTimeout(() => {
        clearTimeout(this.timer)
        this.timer = undefined
      }, 500)
    },
    // 打开了高级搜索弹框
    handlerOpenHighSearch() {
      const searchForm = this.searchForm
      for (const key in searchForm) {
        if (key === 'denyWorder' || key === 'include') {
          this.searchForm[key] = this.queryData.openUpWordCondition[key]
        } else {
          this.searchForm[key].max = this.queryData.openUpWordCondition[key + 'Max'] ? this.queryData.openUpWordCondition[
            key + 'Max'] : undefined
          this.searchForm[key].min = this.queryData.openUpWordCondition[key + 'Min'] ? this.queryData.openUpWordCondition[
            key + 'Min'] : undefined
        }
      }
    },
    // 重置高级搜索表单
    resetSearForm() {
      this.searchForm = {
        include: '', // 包含
        denyWorder: '', // 不包含
        asaPopular: {
          min: undefined,
          max: undefined
        }, // ASA流行度
        asoSearch: {
          min: undefined,
          max: undefined
        }, // App Store搜索指数
        searchCount: {
          min: undefined,
          max: undefined
        }, // App Store搜索结果数
        googleSearch: {
          min: undefined,
          max: undefined
        }, // 谷歌搜索指数
        youtubeSearch: {
          min: undefined,
          max: undefined
        }, // YouTube搜索指数
        baiduPc: {
          min: undefined,
          max: undefined
        }, // 百度Pc搜索指数
        baiduMb: {
          min: undefined,
          max: undefined
        } // 百度移动搜索指数
      }
    },
    // 提交了高级搜索框
    handlerHighSearch() {
      const searchForm = this.searchForm
      for (const key in searchForm) {
        if (key === 'include') {
          this.queryData.openUpWordCondition.include = searchForm.include
        } else if (key === 'denyWorder') {
          this.queryData.openUpWordCondition.denyWorder = searchForm.denyWorder
        } else {
          this.queryData.openUpWordCondition[key + 'Max'] = this.searchForm[key].max ? this.searchForm[key].max
            : undefined
          this.queryData.openUpWordCondition[key + 'Min'] = this.searchForm[key].min ? this.searchForm[key].min
            : undefined
        }
      }
      this.highSearchShow = false
      if (!this.queryData.text) {
        return this.$message.error('请输入关键词进行拓词')
      }
      this.getOpenWords()
    },

    handleToSearch(data) {
      this.searchStr = data.keyword
      this.handleSearch()
    },

    // 点击了添加至按钮
    handleAddTo(data) {
      this.addList = JSON.parse(JSON.stringify(data))
      this.dialogFormVisible = true
    },

    // 取消提交添加
    handleCloseSub() {
      this.$refs.addForm.resetFields()
      this.$nextTick(() => {
        this.dialogFormVisible = false
      })
    },
    // 确定添加至
    handleSubAdd() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          if (this.form.type === 'adgroup') {
            this.addWordToAdgroup()
          } else {
            this.addWordToStore()
          }
        } else {
          return false
        }
      })
    },
    // 添加词到广告组
    async addWordToAdgroup() {
      if (this.form.adList.length) {
        const keywords = this.addList.map(item => {
          console.log(item)
          return {
            text: item.keyword,
            matchType: 'BROAD' // '暂时写死'
          }
        })
        const list = this.form.adList.map(item => {
          console.log(item)
          let data
          if (item[0] === 'default') {
            data = {
              currencyType: this.$store.state.user.unit,
              campaignGroupId: item[1],
              campaignId: item[2],
              adgroupId: item[3],
              orgId: '', // 写死
              uuid: '', // 写死
              keywords,
              teamId: this.$store.state.team.teamId
            }
          } else {
            data = {
              currencyType: this.$store.state.user.unit,
              campaignId: item[2],
              adgroupId: item[3],
              orgId: item[1], // 写死
              uuid: item[0], // 写死
              keywords,
              teamId: this.$store.state.team.teamId

            }
          }
          return data
        })

        const obj = {
          list
        }
        try {
          const res = await recommendWordShiftAdvGroup(obj)
          if (res.data.code * 1 === 20000) {
            this.$message({
              duration: 1500,
              message: res.data.message || '添加词成功',
              type: 'success'
            })
            return this.handleCloseSub()
          } else {
            this.$message({
              duration: 1500,
              message: res.data.message || '添加词失败',
              type: 'error'
            })
          }
        } catch (err) {

        }
      } else {
        return false
      }
    },
    // 添加词到词库
    async addWordToStore() {
      if (this.form.storeList.length) {
        const batch = this.form.storeList.map(item => {
          const obj = {}
          obj.wordUserId = item[1]
          obj.list = this.addList.map(v => {
            return {
              wordUserId: item[1],
              word: v.keyword,
              matchType: 'BROAD'
            }
          })

          return obj
        })

        const res = await addWordsToStore({
          batch
        })
        this.$message.closeAll()
        if (res.data.code * 1 === 20000) {
          this.$message({
            duration: 1500,
            message: res.data.message || '添加词成功',
            type: 'success'
          })
          return this.handleCloseSub()
        } else {
          this.$message({
            duration: 1500,
            message: res.data.message || '添加词失败',
            type: 'error'
          })
        }
      } else {
        return false
      }
    }

  }
}
</script>

<style scoped lang="scss">
.header {
  width: 100%;
  height: 70px;
  position: fixed;
  // left: 0;
  margin-top: -25.7px;
  z-index: 99;
  background: #f9f9f9;
  .header_span {
    position: absolute;
    margin-top: 24px;
    // margin-left: 105px;
  }
}
  .detail-main {
    min-height: calc(100vh - 200px);
  }

  .search-box {
    margin-bottom: 24px;

    .lt-box {
      .title {
        font-size: 14px;
        margin-right: 12px;
      }

      .btn {
        margin-left: 24px;
      }
    }

    .rt {
      font-size: 14px;
      line-height: 14px;
      margin-left: 14px;

      .input-box {
        margin-right: 26px;
        width: 300px;
      }

      em {
        margin: 0 24px
      }

      ::v-deep span {
        font-size: 14px;
        line-height: 14px;
      }
    }
  }

  .hint-rt {
    justify-content: flex-end;

    span {
      margin-left: 24px;
      color: #24BEBE;
    }
  }

  .open-layout .dia ::v-deep .el-dialog__footer {
    border-top: 1px solid #EEEEEE;
  }

</style>
